package com.yssoft.service.production;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.yssoft.common.Constants;
import com.yssoft.entity.core.TDepartment;
import com.yssoft.entity.production.TLabelApply;
import com.yssoft.mapper.core.TDepartmentMapper;
import com.yssoft.mapper.production.TLabelApplyMapper;
import com.yssoft.mapper.production.TLabelsMapper;
import com.yssoft.utils.AppUserHelper;
import com.yssoft.utils.LayuiUtil;
import com.yssoft.utils.MakeEncode;
import com.yssoft.utils.SessionUtil;
import com.yssoft.utils.UserHelper;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称: LabelApplyService
 * @类描述: 标签申请service
 * @作者: 王永宁
 * @创建时间:2018年5月9日 下午5:40:58
 */
@Service
public class LabelApplyService {
	private static Logger logger=Logger.getLogger(LabelApplyService.class);
    @Resource
    private TLabelsMapper labelsMapper;
    @Resource
    private TLabelApplyMapper labelApplyMapper;
    @Resource
    private TLabelsMapper labelMapper;
    @Resource
    private TDepartmentMapper deptMapper;
    /**
     * @方法名称: findPage
     * @功能描述: 获取标签申请列表
     * @作者: 王永宁
     * @创建时间:2018年5月9日 下午7:39:40
     * @param page
     * @param limit
     * @param companyId
     * @param createTime
     * @param productName
     * @param stat
     * @return List<Map<String,Object>>
     */
	public List<Map<String, Object>> findPage(int page, int limit, Integer companyId,
		String createTime, String productName, String stat) {
		HashMap<String,Object> param = new HashMap<>();
        param.put("createTime",createTime);
        param.put("productName",productName);
        param.put("stat",stat);
        param.put("companyId",companyId);
        Integer start = ((page - 1) * limit);
        Integer end = limit;
		param.put("start", start);
		param.put("end", end);
		List<Map<String, Object>>  labelApplyList = labelApplyMapper.selectLabelApply(param);
        return labelApplyList;
    }
    /**
     * @方法名称: save
     * @功能描述: 保存标签申请
     * @作者: 王永宁
     * @创建时间:2018年5月10日 上午10:29:55
     * @param request
     * @param entity void
     */
	public void save(HttpServletRequest request, TLabelApply entity) {
		String code = "SQ" + Calendar.getInstance().getTimeInMillis();
		entity.setDeleteFlag("0");
		entity.setCode(code);
		entity.setCreateTime(new Date());
		entity.setStat("0");
		//TDepartment dept = deptMapper.selectByPrimaryKey(entity.getDeptId());
		//entity.setDeptName(dept.getName());
		entity.setDeptId(AppUserHelper.getCurrentDeptId(request));
		entity.setDeptName(AppUserHelper.getCurrentDeptName(request));

		entity.setInvalidQuantity(new BigDecimal(0));
		entity.setUsedQuantity(new BigDecimal(0));
		entity.setFrozenQuantity(new BigDecimal(0));
		entity.setRecallQuantity(new BigDecimal(0));
		entity.setGrantQuantity(new BigDecimal(0));
		labelApplyMapper.insertSelective(entity);


	}
    /**
     * 分页标签申请信息
     * @param page
     * @param limit
     * @param code
     * @param creatorName
     * @param stat
     * @return
     */
	public JSONObject queryLabelPage(int page, int limit, String code,
			String creatorName, String stat) {
        //获取当前登陆账号信息
        Integer entId =UserHelper.getCurrentCompanyId();//企业id
        PageHelper.startPage(page,limit);//下面第一个查询结果进行分页
        Map<String,Object> param=new HashMap<>();
        param.put("companyId",entId);
        param.put("code",code);
        param.put("creatorName",creatorName);
        param.put("stat", stat);
        List<Map<String,Object>> personList = labelApplyMapper.selectAllSql(param);
        /*for (Map<String, Object> map : personList) {
        	if(map.get("stat").equals("1")){
        		List<Map<String, Object>> labels = labelMapper.selectLabelList(Integer.valueOf(map.get("id").toString()));
        		map.put("type", labels.get(0).get("trace_type"));
        	}
        	if(map.get("stat").equals("0")||map.get("stat").equals("2")){
        		map.put("type", "1");
        	}
		}*/
        int count = labelApplyMapper.selectCountSql(param);//查询条数
        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(personList,count,"","");
        return jsonObject;
	}

	/**
	 * 根据标签申请id查询标签申请
	 * @param labelId
	 * @return
	 */
	public TLabelApply queryLabelApplyById(String labelId) {
		return labelApplyMapper.selectByPrimaryKey(Integer.parseInt(labelId));
	}
	/**
	 * 修改标签申请（标签审批不通过）
	 * @param labelApply
	 */
	public void updateLabelApply(TLabelApply labelApply) {
		labelApplyMapper.updateByPrimaryKey(labelApply);

	}
	/**
	 * 监管标签查看
	 * 王永宁
	 * @param page
	 * @param limit
	 * @param area
	 * @param mType
	 * @param companyId
	 * @param productName
	 * @param suyuan
	 * @return
	 */
	public JSONObject queryLabelPageForSupervise(int page, int limit,String area, String mType, String companyId,String productName,String suyuan) {
		 PageHelper.startPage(page,limit);//下面第一个查询结果进行分页
		 HashMap<String,Object> param=new HashMap<>();
		 param.put("stat","1");
		 // 只添加非空字符串的参数
		 if (area != null && !area.trim().equals("")) {
			 param.put("area",area); //地区
		 }
		 if (suyuan != null && !suyuan.trim().equals("")) {
			 param.put("suyuan",suyuan); //溯源类型
		 }
		 if (mType != null && !mType.trim().equals("")) {
			 param.put("mType",mType); //商品类型
		 }
		 if (productName != null && !productName.trim().equals("")) {
			 param.put("productName",productName); //商品名称
		 }
	        if (companyId!=null&&companyId!="") {
	            String[] ids = companyId.split(",");
	            param.put("ids",ids); //生产企业名称
	        }


	     List<Map<String, Object>>  labelApplyList = labelApplyMapper.selectLabelApply(param);
	     int count = labelApplyMapper.selectLabelApplyCount(param);//查询条数
	        JSONObject jsonObject =LayuiUtil.getJSONObjectByMap(labelApplyList,count,"","");
		return jsonObject;
	}
	public List<Map<String, Object>> exportExcel(HttpServletRequest request, String labelId) {
		List<Map<String, Object>> data =new ArrayList<>();
		String ip =request.getServerName();
		String basePath ="http://"+ip+":"+request.getServerPort()+request.getContextPath()+Constants.QRENCODE_SCAN_PATH;
		List<Map<String, Object>> list = labelsMapper.selectLabelList(Integer.parseInt(labelId));
		if(list!=null && list.size()>0) {
			for(Map<String, Object> map:list) {
				Map<String, Object> excelMap=new HashMap<>();
				if(null!=map.get("code") &&  !"".equals(map.get("code")+"")) {
					String code=map.get("code")+"";
					String url= basePath+code;
					excelMap.put("code", code);
					excelMap.put("url", url);
					data.add(excelMap);
				}

			}
		}
		return data;
	}

	public List<Map<String, Object>> exportLabel(HttpServletRequest request, String workSheetId) {
		List<Map<String, Object>> data =new ArrayList<>();
		String ip =request.getServerName();
		String basePath ="http://"+ip+":"+request.getServerPort()+request.getContextPath()+Constants.QRENCODE_SCAN_PATH;
		List<Map<String, Object>> list = labelsMapper.selectLabelListByWorkSheetId(Integer.parseInt(workSheetId));
		if(list!=null && list.size()>0) {
			for(Map<String, Object> map:list) {
				Map<String, Object> excelMap=new HashMap<>();
				if(null!=map.get("code") &&  !"".equals(map.get("code")+"")) {
					String code=map.get("code")+"";
					String url= basePath+code;
					excelMap.put("code", code);
					excelMap.put("url", url);
					data.add(excelMap);
				}

			}
		}
		return data;
	}


}


